﻿using System;
using System.Net;
using System.Web;
using System.IO;
using System.Configuration;

namespace NIGeoCoding
{
  public static class GeoCoder
  {
    private const string ServiceUrl = "http://maps.google.com/maps/geo?output=json&q={0}&key={1}&oe=utf8&sensor=false";
    private static readonly string accessKey = ConfigurationSettings.AppSettings["accessKey"];

    private static HttpWebRequest BuildWebRequest(string address)
    {
      string url = String.Format(ServiceUrl, HttpUtility.UrlEncode(address), accessKey);
      HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
      req.Method = "GET";
      return req;
    }

    public static Response GeoCode(string address)
    {
      if (String.IsNullOrEmpty(address)) 
        throw new ArgumentNullException("address");

      HttpWebRequest request = BuildWebRequest(address);
      using (HttpWebResponse resp = request.GetResponse() as HttpWebResponse)
      {
        using (StreamReader respReader = new StreamReader(resp.GetResponseStream()))
        {
          string jsonResponse = respReader.ReadToEnd();
          return JSONHelper.Deserialize<Response>(jsonResponse);
        }
      }
    }
  }
}
